var formErrorPlacement = function (error, element) {
    var dem = $('<div class="form-error"/>').append(error);
    $(element).parent().append(dem);
};

var formErrorPlacementNoMsg= function (error, element) {
    var dem = $('<div class="form-error"/>').append(error);
    $(element).parent().append(dem);
};

var REFERER_URL='';
var oauth=function () {

    var ts=this;
    ts.captchaObj=null;
    ts.validation=false;
    ts.reg={
        captchaObj:null,
        validation:null
    };
    ts.referer="";

    var waitSecond=0;

    var init=function () {

        initValidationLogin();

        initValidationReg1();

        initValidationReg2();

        $("#btn_login").click(function () {
            $("#mod_login").dialog({
                width: 507,
                height: 380,
                title: "登录",
                showHead:false
            });
            $("#txt_userName").focus();
            captchaInitLogin();
        });

        $("#btn_reg").click(function () {
            $("#mod_reg").dialog({
                width: 507,
                height: 450,
                title: "注册",
                showHead:false
            });
            $(".regis_tab").children("a").eq(0).click();
            captchaInitReg();
            $("#txt_regUserName").focus();
        });

        $("#gotoReg").click(function () {
            $("#mod_login").dialog("close");
            $("#btn_reg").click();
        });

        $("#gotoLogin").click(function () {
            $("#mod_reg").dialog("close");
            $("#btn_login").click();
        });

        $(".regis_tab").children("a").click(function () {
            if(!$(this).hasClass("tab_on")){
                $(this).parent().children("a").removeClass("tab_on");
                $(this).addClass("tab_on");
                var index=$(this).parent().children("a").index($(this));
                $("#regis_cont").children("div").hide();
                $("#regis_cont").children("div").eq(index).show();
                $("#regis_cont").children("div").eq(index).find('input[type=text]').eq(0).focus();
                if(index==0){
                    captchaInitReg();
                }
                if(index==1 && waitSecond>0){
                    clearInterval(upTimeObj);
                    upTimeObj=setInterval(upTimeInterval,1000);
                    $("#txt_regMobileValCode").focus();
                }
            }
        });

        $("#btn_logintrue").click(function () {
            loginPost();
        });

        $("#btn_regSendSMS").click(function () {
            $("#btn_regSendSMS").attr("disabled","disabled");
            var mobile=$("#txt_regMobile").val().trim();
            if(!AFC.validate.isMobile(mobile)){
                $.artcloud.apop({ type: "error", content: "手机号格式错误." });
                $("#btn_regSendSMS").attr("disabled",false);
                $("#txt_regMobile").focus();
            }else{
                $("#mod_checkInput").dialog({
                    width:400,
                    height: 80,
                    showHead:false,
                    title: "",
                    onclose:function () {
                        $("#btn_regSendSMS").attr("disabled",false).text("获取短信验证码");
                    }
                });
                var dialog= $("#checkInput2").closest(".acui-dialog-box");

                var nc_token = ["FFFF0N00000000006147", (new Date()).getTime(), Math.random()].join(':');
                var nc = NoCaptcha.init({
                    renderTo: '#checkInput2',
                    appkey: 'FFFF0N00000000006147',
                    scene: 'nc_ message',
                    token: nc_token,
                    is_Opt: 0,
                    language: "cn",
                    timeout: 3000,
                    errorTimes: 5,
                    inline: false,
                    bannerHidden:false,
                    apimap: {},
                    callback: function (data) {
                        var postData = {
                            mobile:mobile,
                            sessionId: data.csessionid,
                            sig: data.sig,
                            token: nc_token,
                            scene: "nc_ message"
                        };
                        $.artcloud.loading("正在发送短信...");
                        AFC.ajax.postJSON("/oauth/sendSms",postData,function(rdata){
                            $.artcloud.loading("close");
                            $("#mod_checkInput").dialog("close");
                            if (rdata.status) {
                                $.artcloud.apop({ type: "success", content: "验证码发送成功。" });
                                waitSecond=60;
                                var upTimeObj=setInterval(function () {
                                    if(waitSecond<=0){
                                        $("#btn_regSendSMS").val("获取短信验证码");
                                        $('#btn_regSendSMS').removeAttr("disabled");
                                        clearInterval(upTimeObj);
                                    }else{
                                        $("#btn_regSendSMS").val(waitSecond+"秒后重新获取。");
                                    }
                                    waitSecond--;
                                },1000);
                                $("#txt_regMobileValCode").focus();
                            } else{
                                var msg=rdata.message||"失败";
                                $.artcloud.apop({ type: "error", content: msg });
                            }
                        });
                    },
                    error: function (s) {
                    }
                });
                NoCaptcha.setEnabled(true);
                nc.reset();//请务必确保这里调用一次reset()方法
                NoCaptcha.upLang('cn', {
                    'LOADING': "加载中...",//加载
                    'SLIDER_LABEL': "请滑动鼠标到最右边",//等待滑动
                    'CHECK_Y': "验证通过",//通过
                    'ERROR_TITLE': "非常抱歉，这出错了...",//拦截
                    'CHECK_N': "验证未通过", //准备唤醒二次验证
                    'OVERLAY_INFORM': "经检测你当前操作环境存在风险，请输入验证码",//二次验证
                    'TIPS_TITLE': "验证码错误，请重新输入"//验证码输错时的提示
                });

            }
        });

        $("#btn_regTrue").click(function () {
            var type=$(".regis_tab").children("a").index($(".regis_tab").children(".tab_on"));
            if(type==0){
                regUser();
            }else{
                regMobile();
            }
        });

        $("#txt_userName,#txt_pwd").keydown(function(e){
            var curKey = e.which;
            if (curKey == 13) {
                $("#btn_logintrue").click();
                return false;
            }
        });

        $("#txt_regUserName,#txt_regPwd,#txt_regRePwd,#txt_regValCode,#btn_regREMPwd,#txt_regMobile,#btn_regMPwd,#txt_regMobileValCode").keydown(function(e){
            var curKey = e.which;
            if (curKey == 13) {
                $("#btn_regTrue").click();
                return false;
            }
        });

        var referer= AFC.getQueryString("referer");
        if(referer && referer!=""){
            $("#btn_login").click();
        }
    };

    var loginPost=function (callback) {
        if (!$("#loginForm").valid()) {
            $("#loginForm").find("input.error").eq(0).focus();
            return;
        }
        if(!ts.validation){
            $.artcloud.apop({ type: "error", content: "滑块验证失败。" });
            return;
        }
        var userName=$("#txt_userName").val().trim();
        var pwd=$("#txt_pwd").val().trim();
        $.artcloud.loading("正在登录....");
        AFC.ajax.postJSON("/oauth/login",{userName:userName,pwd:pwd,sessionId:ts.captchaObj.sessionId,sig:ts.captchaObj.sig,token:ts.captchaObj.token,scene:ts.captchaObj.scene},function(rdata){
            $.artcloud.loading("close");
            if (rdata.status) {
                $.artcloud.apop({ type: "success", content: "登录成功！" });
                var referer= AFC.getQueryString("referer");
                if(REFERER_URL && REFERER_URL!=""){
                    window.location=unescape(REFERER_URL);
                }else if(referer && referer!=""){
                    window.location=unescape(referer);
                }else{
                    window.location="/user/index";
                }
                REFERER_URL="";
            } else{
                var msg=rdata.message||"登录失败";
                if(rdata.errorCode && rdata.errorCode=="002"){
                    msg="安全验证未通过。";
                    captchaInitLogin();
                }
                $.artcloud.apop({ type: "error", content: msg });
            }
            if(callback){
                callback(rdata.status);
            }
        });
    };

    var initValidationLogin=function () {
        $("#loginForm").validate({
            rules: {
                txt_userName: {
                    required: true
                },txt_pwd: {
                    required: true
                }
            },
            messages:{
                txt_userName:"用户名以字母开头、可包含数字或下划线的字符。",
                txt_pwd:"密码不能为空"
            },
            errorPlacement: formErrorPlacementNoMsg
        });
    };

    var initValidationReg1=function () {
        $("#regForm1").validate({
            rules: {
                txt_regUserName: {
                    required: true,
                    rangelength:[4,16],
                    charNumber:true
                },txt_regPwd: {
                    required: true,
                    rangelength:[8,16],
                },txt_regRePwd:{
                    required: true,
                    rangelength:[8,16],
                    equalTo:'#txt_regPwd'
                }
            },
            messages:{
                txt_regUserName:"用户名以字母开头、可包含数字或下划线的字符。",
                txt_regPwd:"密码长度为8-16个字符。",
                txt_regRePwd:"密码长度为8-16个字符。"
            },
            errorPlacement: formErrorPlacementNoMsg
        });
    };

    var initValidationReg2=function () {
        $("#regForm2").validate({
            rules: {
                txt_regMobile: {
                    required: true,
                    rangelength:[11,11]
                },txt_regMobileValCode: {
                    required: true,
                    rangelength:[6,6],
                },btn_regMPwd:{
                    required: true,
                    rangelength:[8,16],
                },btn_regREMPwd:{
                    required: true,
                    rangelength:[8,16],
                    equalTo:'#btn_regMPwd'
                }
            },
            messages:{
                txt_regUserName:"请正确输入手机号。",
                txt_regMobileValCode:"请正确输入手机验证码",
                btn_regMPwd:"密码长度为8-16个字符。",
                btn_regREMPwd:"密码长度为8-16个字符。"
            },
            errorPlacement: formErrorPlacementNoMsg
        });
    };

    var captchaInitLogin=function () {
        ts.captchaObj=null;
        ts.validation=false;
        var nc_token = ["FFFF0N00000000006147", (new Date()).getTime(), Math.random()].join(':');
        var nc = NoCaptcha.init({
            renderTo: '#checkInput',
            appkey: 'FFFF0N00000000006147',
            scene: 'nc_ message',
            token: nc_token,
            is_Opt: 0,
            language: "cn",
            timeout: 3000,
            customWidth: 300,
            errorTimes: 5,
            inline: false,
            bannerHidden:false,
            apimap: {},
            callback: function (data) {
                ts.captchaObj = {
                    sessionId: data.csessionid,
                    sig: data.sig,
                    token: nc_token,
                    scene: "nc_ message"
                };
            },
            error: function (s) {

            }
        });
        NoCaptcha.setEnabled(true);
        nc.reset();//请务必确保这里调用一次reset()方法
        NoCaptcha.upLang('cn', {
            'LOADING': "加载中...",//加载
            'SLIDER_LABEL': "请滑动鼠标到最右边",//等待滑动
            'CHECK_Y': "验证通过",//通过
            'ERROR_TITLE': "非常抱歉，这出错了...",//拦截
            'CHECK_N': "验证未通过", //准备唤醒二次验证
            'OVERLAY_INFORM': "经检测你当前操作环境存在风险，请输入验证码",//二次验证
            'TIPS_TITLE': "验证码错误，请重新输入"//验证码输错时的提示
        });
        nc.on("success",function () {
            ts.validation=true;
        });
    };

    var captchaInitReg=function () {
        ts.reg.captchaObj=null;
        ts.reg.validation=false;
        var nc_token = ["FFFF0N00000000006147", (new Date()).getTime(), Math.random()].join(':');
        var nc = NoCaptcha.init({
            renderTo: '#checkInput1',
            appkey: 'FFFF0N00000000006147',
            scene: 'nc_ message',
            token: nc_token,
            is_Opt: 0,
            language: "cn",
            timeout: 3000,
            customWidth: 300,
            errorTimes: 5,
            inline: false,
            bannerHidden:false,
            apimap: {},
            callback: function (data) {
                ts.reg.captchaObj = {
                    sessionId: data.csessionid,
                    sig: data.sig,
                    token: nc_token,
                    scene: "nc_ message"
                };
            },
            error: function (s) {

            }
        });
        NoCaptcha.setEnabled(true);
        nc.reset();//请务必确保这里调用一次reset()方法
        NoCaptcha.upLang('cn', {
            'LOADING': "加载中...",//加载
            'SLIDER_LABEL': "请滑动鼠标到最右边",//等待滑动
            'CHECK_Y': "验证通过",//通过
            'ERROR_TITLE': "非常抱歉，这出错了...",//拦截
            'CHECK_N': "验证未通过", //准备唤醒二次验证
            'OVERLAY_INFORM': "经检测你当前操作环境存在风险，请输入验证码",//二次验证
            'TIPS_TITLE': "验证码错误，请重新输入"//验证码输错时的提示
        });
        nc.on("success",function () {
            ts.reg.validation=true;
        });
    };

    var regUser=function () {
        if (!$("#regForm1").valid()) {
            $("#regForm1").find("input.error").eq(0).focus();
            return;
        }
        if(!ts.reg.validation){
            $.artcloud.apop({ type: "error", content: "滑块验证失败。" });
            return;
        }
        var userName=$("#txt_regUserName").val().trim();
        var pwd=$("#txt_regPwd").val().trim();
        $.artcloud.loading("正在注册....");
        AFC.ajax.postJSON("/oauth/reg",{userName:userName,pwd:pwd,sessionId:ts.reg.captchaObj.sessionId,sig:ts.reg.captchaObj.sig,token:ts.reg.captchaObj.token,scene:ts.reg.captchaObj.scene},function(rdata){
            $.artcloud.loading("close");
            if (rdata.status) {
                $.artcloud.apop({ type: "success", content: "注册成功！" });
                var referer= AFC.getQueryString("referer");
                if(referer && referer!=""){
                    window.location=unescape(referer);
                }else{
                    window.location="/user/index";
                }
            } else{
                var msg=rdata.message||"注册失败";
                if(rdata.errorCode && rdata.errorCode=="002"){
                    msg="安全验证未通过。";
                    captchaInitReg();
                }
                $.artcloud.apop({ type: "error", content: msg });
            }
        });
    };

    var regMobile=function () {
        if (!$("#regForm2").valid()) {
            $("#regForm2").find("input.error").eq(0).focus();
            return;
        }
        var userName=$("#txt_regMobile").val().trim();
        var pwd=$("#btn_regMPwd").val().trim();
        var valCode=$("#txt_regMobileValCode").val().trim();
        $.artcloud.loading("正在注册....");
        AFC.ajax.postJSON("/oauth/reg1",{userName:userName,pwd:pwd,valCode:valCode},function(rdata){
            $.artcloud.loading("close");
            if (rdata.status) {
                $.artcloud.apop({ type: "success", content: "注册成功！" });
                var referer= AFC.getQueryString("referer");
                if(referer && referer!=""){
                    window.location=unescape(referer);
                }else{
                    window.location="/user/index";
                }
            } else{
                var msg=rdata.message||"注册失败";
                $.artcloud.apop({ type: "error", content: msg });
            }
        });
    };

    var isLogin=function () {
        return $("#li_a_userName").length>0?true:false;
    };

    this.init=init;

    this.isLogin=isLogin;

    this.login=function (url) {
        REFERER_URL="";
        if(!isLogin()){
            if(url){
                REFERER_URL=unescape(url);
            }
            $("#btn_login").click();
        }else{
            return true;
        }
    };
};